import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  UseInterceptors,
  UploadedFiles,
  BadRequestException,
} from '@nestjs/common';
import { FilesInterceptor } from '@nestjs/platform-express';
import { GoodsService } from './goods.service';
import { CreateGoodsDto } from './dto/create-goods.dto';
import { UpdateGoodsDto } from './dto/update-goods.dto';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiBearerAuth,
  ApiConsumes,
  ApiBody,
} from '@nestjs/swagger';
import { Goods } from './entities/goods.entity';
import { BufferedFile } from '../minio/file.model';

@ApiTags('商品管理')
@ApiBearerAuth()
@Controller('goods')
export class GoodsController {
  constructor(private readonly goodsService: GoodsService) {}

  @Post()
  @ApiOperation({ summary: '创建商品' })
  @ApiResponse({
    status: 201,
    description: '创建成功',
    type: Goods,
  })
  create(@Body() createGoodsDto: CreateGoodsDto) {
    return this.goodsService.create(createGoodsDto);
  }

  @Post('upload/:id')
  @ApiOperation({ summary: '上传商品图片' })
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    schema: {
      type: 'object',
      properties: {
        files: {
          type: 'array',
          items: {
            type: 'string',
            format: 'binary',
          },
        },
      },
    },
  })
  @UseInterceptors(FilesInterceptor('files'))
  async uploadImages(
    @Param('id') id: string,
    @UploadedFiles() files: BufferedFile[],
  ) {
    if (!files || files.length === 0) {
      throw new BadRequestException('文件不能为空');
    }
    return this.goodsService.uploadImages(+id, files);
  }

  @Get()
  @ApiOperation({ summary: '获取所有商品' })
  @ApiResponse({
    status: 200,
    description: '获取成功',
    type: [Goods],
  })
  findAll() {
    return this.goodsService.findAll();
  }

  @Get(':id')
  @ApiOperation({ summary: '获取指定商品' })
  @ApiResponse({
    status: 200,
    description: '获取成功',
    type: Goods,
  })
  findOne(@Param('id') id: string) {
    return this.goodsService.findOne(+id);
  }

  @Patch(':id')
  @ApiOperation({ summary: '更新商品信息' })
  @ApiResponse({
    status: 200,
    description: '更新成功',
    type: Goods,
  })
  update(@Param('id') id: string, @Body() updateGoodsDto: UpdateGoodsDto) {
    return this.goodsService.update(+id, updateGoodsDto);
  }

  @Delete(':id')
  @ApiOperation({ summary: '删除商品' })
  @ApiResponse({
    status: 200,
    description: '删除成功',
  })
  remove(@Param('id') id: string) {
    return this.goodsService.remove(+id);
  }
}
